package com.ziyun.pop.web.api.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ziyun.pop.common.utils.JsonUtils;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Base64Object;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysLoginInforService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 系统登录相关接口
 * @author zh
 * @date 2018/9/1814:57
 */
@RestController
@RequestMapping("port/sys/")
public class SysLoginControllerApi {

    @Autowired
    private SysUserService sysUserService;

    @Value("${popIndex}")
    private String popIndex;

    @Autowired
    SysLoginInforService sysLoginInforService;
    /**
     * 登录校验
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public R list(@RequestBody Map<String,Object> map,HttpServletRequest request) {
        String userName = (String)map.get("userName");
        String password = (String)map.get("password");
        SysUserEntity sysUserEntity = this.sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                                                                            .eq("username",userName));

        if (sysUserEntity != null && sysUserEntity.getUserId() !=null){
            // 用户名密码正确
            // 再校验密码
            if(ShiroUtils.validatePassword(password, sysUserEntity.getPassword())){
                request.getSession().setAttribute("popUserInfo",JsonUtils.object2String(sysUserEntity));
                return R.ok().put("popUserInfo",sysUserEntity);

            }else {
                return R.error("密码错误");
            }
        }else {
            return R.error("用户名错误,或不存在!");
        }
    }

    @RequestMapping("/updateUser")
    public R updateUser(@RequestBody SysUserEntity sysUserEntity) {
       // 直接更新用户信息
        if(StringUtil.isNotEmpty(sysUserEntity.getPasswordOld())){
            String oldPassword = sysUserEntity.getPasswordOld();
            String temp = ShiroUtils.sha1(oldPassword);
            sysUserEntity.setPassword(temp);
        }
        this.sysUserService.updateById(sysUserEntity);
        return R.ok("更新成功!");
    }

    /**
     * 跳转后台
     * @param request
     * @param response
     */
    @RequestMapping("/jumpBackstage")
    public void jumpBackstage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try{

            String data = request.getParameter("token");
            String re = Base64Object.base64ToString(data);
            re = URLDecoder.decode(re, "UTF-8");
            Map<String, String> dataMap = JsonUtils.getMapJsonToStr(re);
            String userName = dataMap.get("userName");
            String password = dataMap.get("password");

            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            subject.login(token);
            // 记录登录信息
            //sysLoginInforService.saveLoginInfo(userName,"0","登录成功");
        }catch (UnknownAccountException e) {
            throw new RRException(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            throw new RRException("账号或密码不正确");
        }catch (LockedAccountException e) {
            throw new RRException("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            throw new RRException("账户验证失败");
        }
        // 成功则 进行跳转
        WebUtils.redirectToSavedRequest(request, response, "/");
    }

    /**
     * mall商城退出调用
     * @param response
     */
    @RequestMapping("/logOutAdmin")
    public void logOutAdmin(HttpServletResponse response) throws Exception {
        //sysLoginInforService.saveLoginInfo(((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername(),"0","退出成功");
        ShiroUtils.logout();
        response.sendRedirect(popIndex+"/index.do"); //跳转到mall商城首页
    }


}
